@file:Suppress("UNREACHABLE_CODE")

package com.fingersoft.feature.plugins

import android.app.Activity
import android.app.Application
import android.content.Context
import android.net.Uri
import cn.fingersoft.util.BuildConfigUtil
import com.fingersoft.business.BusinessContext
import com.fingersoft.business.bambooCloud.IEPassAuthCallback
import com.fingersoft.common.ICallback
import com.fingersoft.common.IProcessCallback
import com.fingersoft.common.preference.UserAppPreferenceHelper
import com.fingersoft.common.preference.provider.UserIdProvider
import com.fingersoft.feature.filemanager.dao.FileDaoUtils
import com.fingersoft.feature.filemanager.dao.bean.FileBean
import com.fingersoft.feature.filemanager.dao.bean.YunpanFilesBean
import com.fingersoft.feature.filemanager.ui.SelectfolderActivity
import com.fingersoft.feature.newlock.LockManager
import com.fingersoft.feature.newlock.LockManager.Companion.LOCK_TYPE_GESTURE
import com.fingersoft.feature.webview.WebViewManager
import com.fingersoft.im.api.UserAgent
import com.fingersoft.im.api.base.BaseModelCallback2
import com.fingersoft.im.api.base.BaseResponse2
import com.fingersoft.im.event.EventManager
import com.fingersoft.im.utils.AppUtils
import com.fingersoft.im.utils.JSONUtils
import com.fingersoft.im.utils.ToastUtils
import com.fingersoft.plugins.IPluginsContext
import com.fingersoft.plugins.api.*
import com.fingersoft.plugins.file.PlainBaseModelCallback
import com.fingersoft.plugins.pdf.PdfDownLoadListener
import com.fingersoft.theme.ThemeM
import com.fingersoft.util.MyFileBean
import com.fingersoft.util.YunpanFiles
import com.google.gson.Gson
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.FileCallback
import com.lzy.okgo.request.BaseRequest
import okhttp3.Call
import okhttp3.Response
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import java.io.File
import java.net.URLEncoder
import java.text.DecimalFormat

/**
 * Created by wc on 2017/9/28.
 */

class SealPluginsContext(private val application: Application) : IPluginsContext {

    override fun QRCodeFilt(context: Context,text:String?): Boolean {
        if(text.isNullOrEmpty()) return true
        val useBambooCloud = BuildConfigUtil.getBoolean("useBambooCloud")
        val QRPrefix = "EPASS_"
        if (useBambooCloud && text.startsWith(QRPrefix)){
            var mBambooCloudProvider = BusinessContext.mBambooCloudProvider
            if(mBambooCloudProvider !=null){
                mBambooCloudProvider.authByQR(context,text,object : IEPassAuthCallback(){
                    override fun success() {
                        ToastUtils.show("二维码认证成功")
                    }

                    override fun error(msg: String?) {
                        ToastUtils.show("二维码认证失败:$msg")
                    }
                })
            }
            return false
        }
        return true
    }

    override fun saveDownloadFile(bean: MyFileBean) {
        val fileBean =FileBean()
        fileBean.id = bean.id
        fileBean.name = bean.name
        fileBean.size = bean.size
        fileBean.type = bean.type
        fileBean.time = bean.time
        fileBean.localPath = bean.localPath
        FileDaoUtils.instance.saveDownloadFile(fileBean)
    }

    override fun getFileBeanById(id: String?): YunpanFiles {
        val yunpanfilebean = FileDaoUtils.instance.getYunPanFilesById(id!!)
        val yunpanFile = YunpanFiles()
        yunpanFile.id = yunpanfilebean!!.id
        yunpanFile.fileSize = yunpanfilebean.fileSize
        yunpanFile.name = yunpanfilebean.name
        yunpanFile.fileUrl = yunpanfilebean.fileUrl
        yunpanFile.folderId = yunpanfilebean.folderId
        yunpanFile.status = yunpanfilebean.status
        yunpanFile.timestamp = yunpanfilebean.timestamp
        yunpanFile.bytes = yunpanfilebean.bytes

        return yunpanFile

    }
    override fun getMyFileById(id: String?): MyFileBean {
        val bean = FileDaoUtils.instance.getMyFilesById(id!!)
        val fileBean = MyFileBean()
        fileBean.id= bean!!.id
        fileBean.name = bean.name
        fileBean.size = bean.size
        fileBean.type = bean.type
        fileBean.time = bean.time
        fileBean.localPath = bean.localPath

        return fileBean

    }
    override fun startYunFile(context: Context?, url: String?, title: String?, yunfileid: String?) {
        WebViewManager.openWebView(context!!, url!!, title!!,yunfileid!!)
    }
    override fun startMyFile(context: Context?, url: String?, title: String?, myfileid: String?) {
        WebViewManager.openMyFileByWebView(context!!, url!!, title!!,myfileid!!)
    }

    override fun sendYunFile(context: Context, file: File, yunpanFilesBean: YunpanFiles) {
        val uri = Uri.parse("file://" + file.getPath())
        val name = yunpanFilesBean.name
        val size = yunpanFilesBean.bytes
        val localUri = Uri.parse(yunpanFilesBean.fileUrl)
        BusinessContext.im?.sendFileMessage(context, localUri, name, size, uri)
    }

    override fun sendMyFile(context: Context, file: File, yunpanFilesBean: MyFileBean) {
        val uri = Uri.parse("file://" + file.getPath())
        val name = yunpanFilesBean.name
        val size = yunpanFilesBean.size as Long
        val localUri = Uri.parse(yunpanFilesBean.localPath)
        BusinessContext.im?.sendFileMessage(context, localUri, name, size, uri)
    }

    override fun ChangeFile(context: Context?, path: String?, params: String?, callback: ICallback<*>?) {
        OkGo.post(AppUtils.getApiUrl(path, AppUtils.J_ECODE))
                .headers("Emp-Info", JSONUtils.toJsonString(UserAgent(context, AppUtils.getTokenInfo().userToken, AppUtils.getTokenInfo().did)))
                .upJson(params)
                .execute(object : BaseModelCallback2<BaseResponse2<*>>(BaseResponse2::class.java) {
                    override fun onSuccess(getYunPanResponse: BaseResponse2<*>, call: Call, response: Response) {
                        super.onSuccess(getYunPanResponse, call, response)
                        if (AppUtils.showApiSucceedErrorToast(getYunPanResponse)) {
                            callback!!.onError()
                            return
                        }

                        if (getYunPanResponse.data != null) {
                            val gson = Gson()
                            val jsonStr = gson.toJson(getYunPanResponse.data)
                            val result = JSONObject(jsonStr)
                            val foldersList = ArrayList<YunpanFilesBean>()
                            val application = Gson().fromJson(jsonStr, YunpanFilesBean::class.java)
                            foldersList.add(application)
                            FileDaoUtils.instance.saveYunPanFiles(foldersList)
                        }
                        callback!!.onSuccess()
                    }

                    override fun onError(call: Call?, response: Response?, e: Exception?) {
                        super.onError(call, response, e)
                        callback!!.onError()
                    }

                })
    }

    override fun deleteYunPanFilesById(id: String): Boolean {
       return  FileDaoUtils.instance.deleteYunPanFilesById(id)
    }
    override fun deleteMyFilesById(id: String): Boolean {
        return  FileDaoUtils.instance.deleteMyFilesById(id)
    }

    override fun startSelectfolderActivity(context: Context?, fileid: String?) {
        SelectfolderActivity.startSelectfolderActivity(context, "0", null, fileid)
    }
    override fun saveMyFileToYunpan(context: Context?, filename: String?,uri:Uri?) {
        SelectfolderActivity.startSelectfolderActivity(context, "0", filename, uri,true)
    }

    override fun DeleteFolder(context: Context?, path: String?, params: String?, callback: ICallback<*>?) {
        OkGo.post(AppUtils.getApiUrl(path, AppUtils.J_ECODE))
                .headers("Emp-Info", JSONUtils.toJsonString(UserAgent(context, AppUtils.getTokenInfo().userToken, AppUtils.getTokenInfo().did)))
                .upJson(params)
                .execute(object : BaseModelCallback2<BaseResponse2<*>>(BaseResponse2::class.java) {
                    override fun onSuccess(getYunPanResponse: BaseResponse2<*>, call: Call, response: Response) {
                        super.onSuccess(getYunPanResponse, call, response)
                        if (AppUtils.showApiSucceedErrorToast(getYunPanResponse)) {
                            callback!!.onError()
                            return
                        }

                        callback!!.onSuccess()
                    }

                    override fun onError(call: Call?, response: Response?, e: Exception?) {
                        super.onError(call, response, e)
                        callback!!.onError()
                    }

                })
    }


    override fun getPdf(context: Context?, url: String?, callback: PdfDownLoadListener) {

        OkGo.get(url)//
                .tag(this)//
                .headers("Emp-Info", JSONUtils.toJsonString(UserAgent(AppUtils.getTokenInfo().userToken, AppUtils.getTokenInfo().did)))
                .execute(object : FileCallback("", "23412341") {  //文件下载时，可以指定下载的文件目录和文件名
                    override fun onSuccess(file: File, call: Call, response: Response) {
                        callback.onSuccess(file)
                    }

                    override fun downloadProgress(currentSize: Long, totalSize: Long, progress: Float, networkSpeed: Long) {
                        //这里回调下载进度(该回调在主线程,可以直接更新ui)
                        //currentSize totalSize以字节byte为单位
                    }

                    override fun onError(call: Call?, response: Response?, e: java.lang.Exception?) {
                        callback.onError(response.toString())
                    }
                })
    }

    override fun sendMessage(context: Context, url: String?) {
        BusinessContext.im?.sendTextMessage(context, url)
    }

    override fun startWebview(context: Context?, url: String?, title: String?) {
        WebViewManager.openWebView(context!!, url!!, title!!)
    }

    override fun getThemeColorName(): String {
        return ThemeM.themeColorType
    }

    override fun getThemeColor(): Int {
        return ThemeM.themeColor
    }

    override fun isUseTheme(): Boolean {
        return AppUtils.useTheme()
    }

    override fun initLockModule(context: Context) {
        val user = AppUtils.getUser()
        LockManager.instance.init(context, user.password, user.empLivingPhoto, user.realName, user.gender, user.jobNnumber)
    }

    override fun initLockModule() {

    }

    override fun doCheckGesture(context: Context?): Boolean {
        return LockManager.instance.isSetLock(LOCK_TYPE_GESTURE)
    }

    override fun doCheckFingerPrint(context: Context?): Boolean {
        return LockManager.instance.checkFingerprint()
    }

    override fun getUserAppPreferenceHelper(): UserAppPreferenceHelper {
        return UserAppPreferenceHelper(object : UserIdProvider() {
            override fun getUserId(): String {
                return AppUtils.getUser().userId ?: ""
            }
        })
    }


    override fun cancelRequest(tag: String) {
        OkGo.getInstance().cancelTag(tag)
    }

    override fun upLoadFile(context: Activity, path: String, param: UploadFileParam, callback: IProcessCallback<UploadFileData>) {
        OkGo.post(AppUtils.getApiUrl(path, AppUtils.J_ECODE))
                .tag(UploadFileParam.DIRTYPE)
                .headers("Emp-Info", JSONUtils.toJsonString(UserAgent(AppUtils.getTokenInfo().userToken, AppUtils.getTokenInfo().did)))
                .params("file", param.files[0], URLEncoder.encode(param.files[0].name,"UTF-8"))
                .execute(object : BaseModelCallback2<UploadFileResponse2>(UploadFileResponse2::class.java) {
                    override fun onSuccess(uploadFileResponse2: UploadFileResponse2, call: Call, response: Response) {
                        super.onSuccess(uploadFileResponse2, call, response)
                        if (AppUtils.showApiSucceedErrorToast(uploadFileResponse2)) {
                            callback.onError()
                            return
                        }
                        callback.onSuccess(uploadFileResponse2.data)
                    }

                    override fun onError(call: Call?, response: Response?, e: Exception?) {
                        super.onError(call, response, e)
                        callback.onError()
                    }

                    override fun onBefore(request: BaseRequest<*>?) {
                        super.onBefore(request)
                        callback.onBefore()
                    }

                    override fun onAfter(uploadFileResponse2: UploadFileResponse2?, e: Exception?) {
                        super.onAfter(uploadFileResponse2, e)
                        callback.onAfter()
                    }

                    override fun upProgress(currentSize: Long, totalSize: Long, progress: Float, networkSpeed: Long) {
                        callback.updateProgress(currentSize, totalSize, progress, networkSpeed)
                    }
                })
    }

    override fun upLoadFileList(context: Activity, path: String, param: UploadFileParam, callback: IProcessCallback<String>) {
        var request = OkGo.post(AppUtils.getApiUrl(path, AppUtils.J_ECODE))
        param.files?.map {
            request.params("file", it, URLEncoder.encode(it.name, "UTF-8"))
        }
        request.tag(UploadFileParam.DIRTYPE)
            .headers("Emp-Info", JSONUtils.toJsonString(UserAgent(AppUtils.getTokenInfo().userToken, AppUtils.getTokenInfo().did)))

        request.execute(object : PlainBaseModelCallback<String>() {
                override fun onSuccess(uploadFileResponse2: String, call: Call, response: Response) {
                    super.onSuccess(uploadFileResponse2, call, response)
                    if (null == uploadFileResponse2) {
                        callback.onError()
                        return
                    }

                    callback.onSuccess(uploadFileResponse2)
                }

                override fun onError(call: Call?, response: Response?, e: Exception?) {
                    super.onError(call, response, e)
                    callback.onError()
                }

                override fun onBefore(request: BaseRequest<*>?) {
                    super.onBefore(request)
                    callback.onBefore()
                }

                override fun onAfter(uploadFileResponse2: String?, e: Exception?) {
                    super.onAfter(uploadFileResponse2, e)
                    callback.onAfter()
                }

                override fun upProgress(currentSize: Long, totalSize: Long, progress: Float, networkSpeed: Long) {
                    callback.updateProgress(currentSize, totalSize, progress, networkSpeed)
                }
            })
    }

    override fun downLoadFile(context: Activity, path: String, param: DownloadFileParam, callback: IProcessCallback<DownloadFileData>) {
        OkGo.post(AppUtils.getApiUrl(path, AppUtils.J_ECODE))
                .tag(UploadFileParam.DIRTYPE)
                .headers("Emp-Info", JSONUtils.toJsonString(UserAgent(AppUtils.getTokenInfo().userToken, AppUtils.getTokenInfo().did)))
                .params("media_id", param.media_id)
                .execute(object : FileCallback() {

                    override fun onSuccess(file: File, call: Call, response: Response) {
                        val downloadFileData = DownloadFileData()
                        downloadFileData.localId = file.path
                        callback.onSuccess(downloadFileData)
                    }

                    override fun onBefore(request: BaseRequest<*>?) {
                        callback.onBefore()
                    }

                    override fun onError(call: Call?, response: Response?, e: Exception?) {
                        callback.onError()
                    }

                    override fun onAfter(file: File?, e: Exception?) {
                        callback.onAfter()
                    }

                    override fun downloadProgress(currentSize: Long, totalSize: Long, progress: Float, networkSpeed: Long) {
                        callback.updateProgress(currentSize, totalSize, progress, networkSpeed)
                    }
                })
    }

    /**
     * @param fileName 为空表示以服务端源文件名称命名
     */
    override fun downLoadFile(context: Activity?, path: String?, param: DownloadFileParam, desPath: String?,
                              fileName: String?, callback: IProcessCallback<DownloadFileData>) {
        OkGo.post(AppUtils.getApiUrl(path, AppUtils.J_ECODE))
            .tag(UploadFileParam.DIRTYPE)
            .headers("Emp-Info", JSONUtils.toJsonString(UserAgent(AppUtils.getTokenInfo().userToken, AppUtils.getTokenInfo().did)))
            .params("media_id", param.media_id)
            .execute(object : FileCallback(desPath, fileName) {

                override fun onSuccess(file: File, call: Call, response: Response) {
                    val downloadFileData = DownloadFileData()
                    downloadFileData.localId = file.path
                    callback.onSuccess(downloadFileData)
                }

                override fun onBefore(request: BaseRequest<*>?) {
                    callback.onBefore()
                }

                override fun onError(call: Call?, response: Response?, e: Exception?) {
                    callback.onError()
                }

                override fun onAfter(file: File?, e: Exception?) {
                    callback.onAfter()
                }

                override fun downloadProgress(currentSize: Long, totalSize: Long, progress: Float, networkSpeed: Long) {
                    callback.updateProgress(currentSize, totalSize, progress, networkSpeed)
                }
            })
    }

    /* 手势 */
    override fun doGestureLock(context: Context) {
        val lockManager = LockManager.instance
        if (lockManager.isSetLock(LOCK_TYPE_GESTURE)) {
            val user = AppUtils.getUser()
            lockManager.init(context, user.password, user.empLivingPhoto, user.realName, user.gender, user.jobNnumber)
            lockManager.doUnLock(3002)
        } else {
            EventBus.getDefault().post(EventManager.OnUnLockFail("没有设置手势密码"))
        }
    }

    //指纹
    override fun doFingerPrintLock(context: Context) {
        if (LockManager.instance.isSetFingerprint()) {
            val user = AppUtils.getUser()
            LockManager.instance.init(context, user.password, user.empLivingPhoto, user.realName, user.gender, user.jobNnumber)
            LockManager.instance.doUnLock(3003)
        } else {
            EventBus.getDefault().post(EventManager.OnUnLockFail("没有设置指纹密码"))
        }
    }

    companion object {

        fun readableFileSize(size: Long): String {
            if (size <= 0) return "0"
            val units = arrayOf("B", "KB", "MB", "GB", "TB")
            val digitGroups = (Math.log10(size.toDouble()) / Math.log10(1024.0)).toInt()
            return DecimalFormat("#,##0.#").format(size / Math.pow(1024.0, digitGroups.toDouble())) + " " + units[digitGroups]
        }
    }
}
